package com.lmy.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lmy.common.utils.PageUtils;
import com.lmy.common.utils.Query;
import com.lmy.product.entity.CategoryEntity;
import com.lmy.product.mapper.CategoryDao;
import com.lmy.product.service.CategoryBrandRelationService;
import com.lmy.product.service.CategoryService;
import com.lmy.vo.CategoryLevelVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryDao categoryDao;
    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //查出所有的列表
        List<CategoryEntity> categoryEntities = categoryDao.selectList(null);
        // 组装成父子的树形结构
        List<CategoryEntity> levelMenus = categoryEntities.stream().filter(categoryEntity ->
                categoryEntity.getParentCid() == 0).map(menu -> {
            menu.setChildren(getChildrens(menu, categoryEntities));
            return menu;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return levelMenus;
    }

    @Override
    public void removeMenusByIds(List<Long> list) {
        //TODO 检查当前删除的菜单，是否被别的地方引用
        baseMapper.deleteBatchIds(list);
    }

    /**
     * 获取catelogId完整的路径
     *
     * @param catelogId
     * @return
     */
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        findParentPath(catelogId, paths);
        // 反转集合
        Collections.reverse(paths);
        return  paths.toArray((new Long[paths.size()]));
    }

    /**
     * 更新关联数据
     * @param category
     */
    @Override
    @Transactional
    public void updateDetail(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
        // TODO 更新其他关联表数据

    }

    @Override
    public List<CategoryEntity> selectOneLevel() {
        return categoryDao.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
    }

    @Override
    public Map<String, List<CategoryLevelVo>> getCatalogJson(){
        String json = stringRedisTemplate.opsForValue().get("catalogJson");
        if (StringUtils.isEmpty(json)){
            System.out.println("缓存不命中，查询数据库、、、、、、、、、");
            return getCatalogJsonFromDB();
        }
        System.out.println("缓存命中，直接返回。。。。。。。。。。");
        return JSON.parseObject(json, new TypeReference<Map<String, List<CategoryLevelVo>>>() {});
    }

    public Map<String, List<CategoryLevelVo>> getCatalogJsonFromDBRedissonLock() {

        Map<String, List<CategoryLevelVo>> dataFromDb;
        dataFromDb = getDataFromDB();

            return dataFromDb;


    }
    private Map<String, List<CategoryLevelVo>> getDataFromDB() {
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        //查询所有的一级分类
        List<CategoryEntity> category1Level = getParentCid(selectList,0L);
        Map<String, List<CategoryLevelVo>> parent_cid = category1Level.stream().collect(
                Collectors.toMap(k -> k.getCatId().toString(), v -> {
                    //根据一级分类查二级分类
                    List<CategoryEntity> categoryEntities = getParentCid(selectList,v.getCatId());
                    List<CategoryLevelVo> categoryLevelVos = null;
                    if (!categoryEntities.isEmpty()) {
                        categoryLevelVos = categoryEntities.stream().map(l2 -> {

                            CategoryLevelVo categoryLevelVo = new CategoryLevelVo(
                                    v.getCatId().toString(),
                                    null,
                                    l2.getCatId().toString(),
                                    l2.getName());
                            //根据二级分类查三级分类
                            List<CategoryEntity> categoryLevel3 = getParentCid(selectList,l2.getCatId());
                            if (!categoryLevel3.isEmpty()){
                                List<CategoryLevelVo.CategoryLevelVo2> categoryLevelVo2s = categoryLevel3.stream().map(l3 -> {
                                    return new CategoryLevelVo.CategoryLevelVo2(l3.getCatId().toString(), l3.getName(),l2.getCatId().toString());
                                }).collect(Collectors.toList());
                                categoryLevelVo.setCatalog3List(categoryLevelVo2s);
                            }
                            return categoryLevelVo;
                        }).collect(Collectors.toList());
                    }
                    return categoryLevelVos;
                }));
        return parent_cid;
    }

    public Map<String, List<CategoryLevelVo>> getCatalogJsonFromDB() {
        /**
         * 将数据库的多次查询，变为一次查询
         */
        synchronized (this){
            String json = stringRedisTemplate.opsForValue().get("catalogJson");
            if (!StringUtils.isEmpty(json)){
                return JSON.parseObject(json, new TypeReference<Map<String, List<CategoryLevelVo>>>() {});
            }
            System.out.println("查询了数据库。。。。。。"+Thread.currentThread().getId());
            Map<String, List<CategoryLevelVo>> parent_cid = getDataFromDB();
            stringRedisTemplate.opsForValue().set("catalogJson", JSON.toJSONString(parent_cid),1, TimeUnit.DAYS);

            return parent_cid;
        }

    }

    private List<CategoryEntity> getParentCid(List<CategoryEntity> selectList,Long parent_cid) {
        return  selectList.stream().filter(item->StringUtils.pathEquals(item.getParentCid().toString(),parent_cid.toString())).collect(Collectors.toList());
    }


    private void findParentPath(Long catelogId, List<Long> paths) {
        paths.add(catelogId);
        CategoryEntity categoryEntity = this.getById(catelogId);
        if (categoryEntity.getParentCid() != 0) {
            findParentPath(categoryEntity.getParentCid(), paths);
        }

    }

    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {
        return all.stream().filter(categoryEntity -> {
            return Objects.equals(categoryEntity.getParentCid(), root.getCatId());
        }).map(categoryEntity -> {
            categoryEntity.setChildren(getChildrens(categoryEntity, all));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
    }
}